//
//  WBMainViewController.swift
//  WeiBoApp
//
//  Created by James on 2017/6/11.
//  Copyright © 2017年 James. All rights reserved.
//

import UIKit

class WBMainViewController: UITabBarController {
    
    fileprivate var timer: Timer?
    
    //主控制
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setUpChildVC()
        addComposeButton()
        setupTimer()
        setupFeatureViews()
        
        delegate = self;
        
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
    }
    
    @objc fileprivate func userLogin(n:Notification){
//        print("用户登录通知 \(n)")
       let vc = UINavigationController(rootViewController: WBOAuthViewController())
            
        present(vc, animated: true, completion: nil)
        
    }
    
    deinit {
        timer?.invalidate()
        //注销通知
        NotificationCenter.default.removeObserver(self)
    }
    
    //设备支持方向,设置之后，当前控制器及其子控制器都会遵循这个方向
    //如果播放视频，通常通过modal展现的
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
       
        return .portrait;
    }
    
    // MARK: - 点击事件
    //@objc 允许这个函数，在运行时通过OC的消息机制被调用
    @objc fileprivate func composeStatus()  {
        print("123")
    }
    
    // MARK: - 私有控件
    fileprivate lazy var composeButton:UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 128/2.0+4, height:88/2.0))

}

extension WBMainViewController {
    // MARK: -新特性试图
    fileprivate func setupFeatureViews(){
        if !WBNetWorkManger.shared.userLogon{ //没登录就返回
            return
        }
        
        //1.检查版本是否更新
        let v = isNewVersion ? WBNewFeatureView.newFeatureView() : WBWelcomeView.welcomeView()
        v.frame = view.bounds
        //2.如果更新  显示新特性 否则显示欢迎页
        
        //3.添加试图
        view.addSubview(v)
    }
    
    ///extension 中可以有计算型属性，不会占用存储空间
    ///构造函数：给属性分配空间
    fileprivate var isNewVersion:Bool{
        
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        print(currentVersion)
        //1.取得当前的版本号
        
        //2.取保存在 document(iTUnes备份)
        let path:String = FileManager.documentsPath().appending("/version.txt")
        let sandBoxVersion = try? String(contentsOfFile: path)
        print(path)
        
        //3.将当前版本号保存沙盒
        try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        //4.返回两个版本号是否一致
        
        return currentVersion != sandBoxVersion
    }
}

///关于时钟的方法
extension WBMainViewController{
    //初始化定时器
    fileprivate func setupTimer(){
        timer = Timer.scheduledTimer(timeInterval:30 ,target: self, selector:#selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    //定时器方法
    @objc fileprivate func updateTimer(){
        
        if !WBNetWorkManger.shared.userLogon{
            return
        }
        
        WBNetWorkManger.shared.unreadCount { (count) in
            //设置标签itme  badgeNumber
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            
            //设置app的
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
    
}

// MARK: - UITabBarControllerDelegate
extension WBMainViewController:UITabBarControllerDelegate {
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        print("将要切换到 \(viewController)")
        
        let idx = (viewControllers as! NSArray).index(of: viewController)
        if selectedIndex == 0 && idx == 0{
            print("点击了首页")
            //重复点击按钮  表格滚回到顶部
            let nav = viewControllers?[0] as! UINavigationController
            let vc = nav.viewControllers[0] as! WBBaseViewController
            
            vc.tableView?.setContentOffset(CGPoint(x:0,y:-64), animated: true)
            
            //刷新数据
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1){
              vc.loadData()  
            }
            
            
            //清除角标数字
            vc.tabBarItem.badgeValue = nil
            
            UIApplication.shared.applicationIconBadgeNumber = 0
            
        }
        
        return !viewController.isMember(of: UIViewController.self)
    }
}

//extension 类似于OC中的分类，在swift中还可以用来切分代码块，
//可以把相近功能的函数，放在一个extension钟
//便于代码维护
//注意：和OC的分类一样，extension 中不能定义属性
extension WBMainViewController {
    fileprivate func addComposeButton(){
        tabBar.addSubview(composeButton)
        composeButton.setBackgroundImage(UIImage.init(named: "tabbar_compose_button"), for: .normal)
        composeButton.center = CGPoint(x: tabBar.bounds.width/2.0, y:  tabBar.bounds.height/2.0)
        composeButton.setImage(UIImage.init(named: "tabbar_compose_icon_add"), for: .normal)
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    }
    
    
    /**
     //关键字说明：
     在swift 3.0 之前，swift 提供3种不同的访问级别
     
     1.public(公开)
     
     2.internal(内部)–>系统默认
     
     3.private(私用)
     
     swift 3.0 private 将会被重新命名为 fileprivate
     
     1.public(公开)
     
     2.internal(内部)
     
     3.fileprivate文件内私有)
     
     4.private(私有)
     */

    fileprivate func setUpChildVC(){
        //冲bundle加载配置的json
        //1.获取沙盒里的json
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        //2.加载data
        var data = NSData(contentsOfFile: jsonPath)
        //如果空，加载bundle里的
        if data == nil {
            let path = Bundle.main.path(forResource: "1.json", ofType: nil)
            data =  NSData(contentsOfFile: path!)
        }
    
        //data一定存在
        guard let array =  try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String:Any]]
            else{
            return
        }

        
//        let array:[[String:Any]] = [["clsName":"WBHomeViewController","title":"首页","imageName":"home","visitorInfo":["imageName":"","message":"关注一些人，回这里看看有什么惊喜"]],
//                     ["clsName":"WBMessageViewController","title":"消息","imageName":"message_center","visitorInfo":["imageName":"visitordiscover_image_message","message":"登陆后，别人评论你的微博，给你发的消息，都会在这里收到通知。"]],
//                     ["clsName":"VC"],
//                    ["clsName":"WBDiscoverViewController","title":"发现","imageName":"discover","visitorInfo":["imageName":"visitordiscover_image_message","message":"登录后，最新、最热微博尽在掌握，不再会与时事潮流擦肩而过"]],
//                    ["clsName":"WBProfileViewController","title":"我的","imageName":"profile","visitorInfo":["imageName":"visitordiscover_image_profile","message":"登录后，你的相册、个人资料会现在在这里，展示给别人"]]
//                     ]
        var arrayM = [UIViewController]()
        
        for dict in array! {
            arrayM.append(controller(dict: dict))
        }
        
        viewControllers = arrayM
        
        //写成文件
//        (array as NSArray).write(toFile: "/Users/mac/Desktop/知识点截图/1.plist", atomically: true)
        //写成json
//        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
//        let filePath = NSURL.fileURL(withPath: "/Users/mac/Desktop/知识点截图/1.json")
//        (data as NSData).write(to: filePath, atomically: true)
//        
        
    }
    
     /// 使用字典创建一个子控制器
     ///
     /// - Parameter dict: [clsName,title,imageName]
     /// - Returns: 子控制器
    fileprivate func controller(dict:[String:Any]) -> UIViewController {
        guard let clsName = dict["clsName"] as? String,
        let title = dict["title"]  as? String,
        let imageName = dict["imageName"]  as? String,
        let VCClass = NSClassFromString(Bundle.main.nameSpace2 + "." + clsName) as?UIViewController.Type,
            let infoDict:[String:String] = dict["visitorInfo"] as? Dictionary
        else {
            return UIViewController()
        }
        
        
        let vc = VCClass.init()
        vc.tabBarItem.image = UIImage(named: "tabbar_"+imageName)
//        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_"+imageName+"_selected" )?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_"+imageName+"_selected" )
       
        vc.title = title;
        (vc as! WBBaseViewController).visitorInfoDict = infoDict
        //设置tabbar的标题字体
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 13)], for: .normal)
        
        let nav = WBNavViewController(rootViewController: vc);
        
        return nav
    }
}
